<template>
  <view class="container">
    <view class="time-selector">
      <view style="width: 100px;">
        <up-subsection :list="timeTabs" :current="isWeekMode ? 0 : 1" @change="handleTimeTabChange" />
      </view>

      <view class="week-range-selector">
        <text @click="prev" class="arrow">＜</text>
        <text class="range-text">{{ timeRangeText }}</text>
        <text @click="next" class="arrow">＞</text>
      </view>
    </view>

    <u-tabs :list="tabs" @click="clickTab" :current="currentTabIndex"></u-tabs>

    <view class="panel-list">
      <scroll-view class="panel-list" scroll-y>
        <u-collapse>
          <u-collapse-item v-for="(item, index) in panelData" :key="index" :title="item.title" class="panel-card">
            <view>{{ item.content }}</view>
          </u-collapse-item>
        </u-collapse>
      </scroll-view>
    </view>
  </view>
</template>

<script>
export default {
  props: {
    params: {
      type: Object,
      required: true,
      validator: function (value) {
        return 'selectedYear' in value && 'start' in value;
      }
    }
  },
  data () {
    return {
      isWeekMode: this.params.title === '团队周统计',
      currentYear: this.params.selectedYear,
      currentMonth: this.params.selectedMonth,
      currentWeekIndex: 0,
      weekList: [],
      timeTabs: [{ name: "周" }, { name: "月" }],
      selectedWeekRange: null,
      currentTabIndex: 0,
      tabs: [
        { name: "平均工时" }, { name: "迟到" }, { name: "早退" }, { name: "缺卡" },
        { name: "旷工" }, { name: "外勤" }, { name: "加班" }, { name: "出差" },
        { name: "外出" }, { name: "丧假" }, { name: "事假" }, { name: "产假" },
        { name: "婚假" }, { name: "年假" }, { name: "病假" }, { name: "陪产假" },
      ],
      panelData: [
        { title: "平均工时 8.9小时", content: "本周平均每日工时8.9小时" },
        { title: "出勤天数 5天", content: "共出勤5天" },
        { title: "出勤班次 2个", content: "早班、晚班" },
        { title: "休息天数 2天", content: "本周休息2天" },
        { title: "迟到 0次", content: "无迟到记录" },
        { title: "早退 0次", content: "无早退记录" },
        { title: "缺卡 0次", content: "无缺卡" },
        { title: "旷工 0天", content: "无旷工" },
        { title: "外勤 0次", content: "无外勤" },
      ]
    };
  },
  computed: {
    timeRangeText () {
      return this.isWeekMode
        ? this.weekList[this.currentWeekIndex] || ""
        : `${this.currentYear}-${String(this.currentMonth).padStart(2, '0')}`;
    }
  },
  watch: {
    params: {
      handler: function ({ selectedYear, selectedMonth, start, title }) {
        this.currentYear = selectedYear;
        this.currentMonth = selectedMonth;
        this.isWeekMode = title === '团队周统计' || title === '个人周统计';

        if (this.isWeekMode) {
          this.updateWeekList(this.parseDateString(start).getTime());
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted () {
    console.log('props', this.params);
    if (!this.params.start) {
      this.$set(this.params, 'start', "01.01"); // 设置默认值
    }
    this.updateWeekList();
  },
  methods: {
    // 获取当前月份的周数
    getWeeksOfMonth (year, month) {
      const weeks = [];
      const date = new Date(year, month - 1, 1);
      date.setDate(date.getDate() - (date.getDay() || 7) + 1); // 定位到当月第一个周一

      do {
        const start = new Date(date);
        const end = new Date(date.setDate(date.getDate() + 6));

        weeks.push({
          start: start.getTime(),
          end: end.getTime(),
          label: `${this.formatDate(start)}–${this.formatDate(end)}`
        });

        date.setDate(date.getDate() + 1);
      } while (date.getMonth() + 1 <= month && date.getFullYear() === year)

      return weeks;
    },
    // 更新当前周
    updateWeekList (targetTimestamp = null) {
      const weeks = this.getWeeksOfMonth(this.currentYear, this.currentMonth);
      this.weekList = weeks.map(w => w.label);

      let index = 0;
      if (targetTimestamp) {
        index = weeks.findIndex(w => targetTimestamp >= w.start && targetTimestamp <= w.end);
      } else {
        const fallbackTime = this.parseDateString(this.params.start).getTime();
        index = weeks.findIndex(w => fallbackTime >= w.start && fallbackTime <= w.end);
      }

      this.currentWeekIndex = index !== -1 ? index : 0;

      // 存储当前周的范围
      const current = weeks[this.currentWeekIndex];
      this.selectedWeekRange = { start: current.start, end: current.end };
    },
    // 更新周列表
    adjustMonth (isNext) {
      let year = this.currentYear;
      let month = this.currentMonth + (isNext ? 1 : -1);

      if (month > 12) {
        year++;
        month = 1;
      } else if (month < 1) {
        year--;
        month = 12;
      }

      return { year, month };
    },
    // 格式化日期
    formatDate (date) {
      return [
        String(date.getMonth() + 1).padStart(2, '0'),
        String(date.getDate()).padStart(2, '0')
      ].join('.');
    },
    // 解析日期字符串
    parseDateString (str) {
      if (!str) {
        console.error("Invalid date string:", str);
        return new Date(this.currentYear, 0, 1); // 返回默认日期
      }
      const [month, day] = str.split('.').map(Number);
      return new Date(this.currentYear, month - 1, day);
    },
    // 上一页
    prev () {
      if (this.isWeekMode) {
        if (this.currentWeekIndex > 0) {
          this.currentWeekIndex--;
        } else {
          const { year, month } = this.adjustMonth(false);
          this.currentYear = year;
          this.currentMonth = month;
          this.updateWeekList();
          this.currentWeekIndex = this.weekList.length - 1;
        }
      } else {
        const { year, month } = this.adjustMonth(false);
        this.currentYear = year;
        this.currentMonth = month;
      }
    },
    // 下月
    next () {
      if (this.isWeekMode) {
        if (this.currentWeekIndex < this.weekList.length - 1) {
          this.currentWeekIndex++;
        } else {
          const { year, month } = this.adjustMonth(true);
          this.currentYear = year;
          this.currentMonth = month;
          this.updateWeekList();
          this.currentWeekIndex = 0;
        }
      } else {
        const { year, month } = this.adjustMonth(true);
        this.currentYear = year;
        this.currentMonth = month;
      }
    },
    // 切换周
    handleTimeTabChange (index) {
      if (!this.isWeekMode) {
        // 当前是"月"，准备切换为"周"，需要记录当前月时间（已由 currentMonth.value 保证）
      } else {
        // 当前是"周"，即将切换为"月"，记录当前周的时间戳
        const weeks = this.getWeeksOfMonth(this.currentYear, this.currentMonth);
        const current = weeks[this.currentWeekIndex];
        if (current) {
          this.selectedWeekRange = { start: current.start, end: current.end };
        }
      }

      this.isWeekMode = index === 0;

      if (this.isWeekMode) {
        const timeToUse = this.selectedWeekRange?.start || this.parseDateString(this.params.start).getTime();
        this.updateWeekList(timeToUse); // 传 timestamp
      }
    },
    // 切换tabs
    clickTab (item) {
      this.currentTabIndex = item.index;
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 10px;

  .time-selector {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;

    .week-range-selector {
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 10px 0;
      font-size: 16px;
      color: #999;

      .arrow {
        margin: 0 10px;
        cursor: pointer;
      }

      .range-text {
        min-width: 120px;
        text-align: center;
      }
    }
  }

  .panel-list {
    margin-top: 10px;
  }
}

.panel-list {
  max-height: 82vh;
  overflow-y: auto;

  ::v-deep .u-collapse-item {
    margin-bottom: 10px;
    border-radius: 12px;
    background-color: #fff;
  }

  ::v-deep .u-collapse-item__title {
    font-size: 14px;
    color: #666;
    padding: 12px 0;
  }

  ::v-deep .u-collapse-item__body {
    font-size: 13px;
    color: #999;
    padding-bottom: 12px;
  }
}
</style>